<template>
  <div
    style="min-height: 100%; overflow: auto; background-color: snow"
    v-title
    data-title="核对订单"
  >
    <h3 style="text-align: left; margin-left: 5%; margin-bottom: 5px">
      填写并核对订单
    </h3>
    <div class="main">
      <div style="border-bottom: solid 1px #c0c0f1; width: 100%">
        <div class="header" style="width: 100%">
          <h4>交易方式</h4>
        </div>
        <div>
          <div style="margin-left: 5%; margin-bottom: 30px; display: flex">
            <el-radio v-model="radio1" label="线上" border> 快递发货 </el-radio>
            <el-radio
              v-show="goodInfo.length == 1"
              v-model="radio1"
              label="线下"
              border
              @change="downLine"
            >
              线下面交
            </el-radio>
          </div>
        </div>
      </div>
      <div
        v-show="radio1 == '线上'"
        style="border-bottom: solid 1px #c0c0f1; width: 100%"
      >
        <div
          class="header"
          style="width: 100%; display: flex; justify-content: space-between"
        >
          <div>
            <h4>收货人信息</h4>
          </div>
          <div style="margin: auto 0; margin-right: 5%">
            <el-button type="success" plain @click="addVisable = true"
              >新增</el-button
            >
          </div>
          <el-dialog
            title="请填写您的收货信息"
            :visible.sync="addVisable"
            width="40%"
            :before-close="handleClose"
            center
          >
            <div>
              <el-form
                :model="addAddressInfoTemp"
                status-icon
                :rules="rules"
                ref="addAddressInfoTemp"
                style="margin-left: 2%; width: 100%"
              >
                <div>
                  <el-form-item
                    label="收货人姓名"
                    label-width="120px"
                    prop="grNameTemp"
                    style="text-align: left"
                  >
                    <el-col :span="18">
                      <el-input
                        type="text"
                        placeholder="请输入您的收货人姓名"
                        v-model="addAddressInfoTemp.grNameTemp"
                        style="width: 100%"
                      />
                    </el-col>
                  </el-form-item>
                  <el-form-item
                    label="收货人电话"
                    label-width="120px"
                    prop="grPhoneTemp"
                    style="text-align: left"
                  >
                    <el-col :span="18">
                      <el-input
                        type="text"
                        @input="grPhoneInput"
                        placeholder="请输入您的收货人电话"
                        v-model="addAddressInfoTemp.grPhoneTemp"
                        style="width: 100%"
                      />
                    </el-col>
                  </el-form-item>
                  <el-form-item
                    label="所在地区"
                    label-width="120px"
                    prop="location"
                    style="text-align: left"
                  >
                    <el-cascader
                      v-model="addAddressInfoTemp.location"
                      :options="locationTree"
                      style="width: 75%"
                    >
                    </el-cascader>
                  </el-form-item>
                  <el-form-item
                    label="详细地址"
                    label-width="120px"
                    prop="grSpecificAddrTemp"
                    style="text-align: left"
                  >
                    <el-col :span="18">
                      <el-input
                        type="text"
                        placeholder="请输入详细的收货地址"
                        v-model="addAddressInfoTemp.grSpecificAddrTemp"
                        style="width: 100%"
                      />
                    </el-col>
                  </el-form-item>
                </div>
              </el-form>
              <div style="margin-top: 10px; margin-left: 30%; text-align: left">
                <el-button
                  size="middle"
                  style="margin-right: 10%"
                  @click="resetForm('addAddressInfoTemp')"
                >
                  重 置
                </el-button>
                <el-button
                  type="primary"
                  size="middle"
                  @click="addAddressSave('addAddressInfoTemp')"
                >
                  保 存
                </el-button>
              </div>
            </div>
          </el-dialog>
        </div>
        <div class="addressTable">
          <el-table
            ref="singleTable"
            :data="addressInformation"
            highlight-current-row
            @current-change="handleCurrentChange"
            style="
              font-size: 20px;
              width: 90%;
              margin-top: 10px;
              margin-left: 5%;
              margin-bottom: 5%;
              max-height: 300px;
            "
          >
            <el-table-column type="index" width="35">
              <template slot-scope="scope">
                <el-radio v-model="radio" :label="scope.row"></el-radio>
              </template>
            </el-table-column>
            <el-table-column property="grName" label="收货人姓名" width="120">
            </el-table-column>
            <el-table-column property="grPhone" label="收货人电话" width="150">
            </el-table-column>
            <el-table-column label="收货地址">
              <template slot-scope="scope">
                <div>
                  {{ scope.row.grProvinces }}{{ scope.row.grCity
                  }}{{ scope.row.grPrefecture }}{{ scope.row.grSpecificAddr }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div style="border-bottom: solid 1px #c0c0f1; width: 100%">
        <div class="header" style="width: 100%">
          <h4>商品清单</h4>
        </div>
        <div
          class="good"
          style="margin: 0 0%; border: solid 1px #f4f4f4; margin-bottom: 30px"
        >
          <!-- <div style="height: 120px; background: #f4f4f4; padding: 15px">
            <div class="header" style="width: 100%; margin-left: 1%">
              <h4>配送方式</h4>
            </div>
            <div style="margin-left: 5%; margin-bottom: 30px">
              <div>
                <span
                  style="
                    float: left;
                    border: 1px solid #ddd;
                    width: 120px;
                    height: 30px;
                    line-height: 30px;
                    text-align: center;
                    margin-right: 10px;
                  "
                >
                  顺丰快递
                </span>
                <p style="line-height: 30px">
                  配送时间：预计两天后09:00-15:00送达
                </p>
              </div>
            </div>
          </div> -->
          <div style="margin-top: 2px; background: #feedef; padding: 15px">
            <div class="header" style="width: 100%; margin-left: 1%">
              <div>
                <ul
                  v-for="order in goodInfo"
                  :key="order.id"
                  style="padding-left: 0px"
                >
                  <div class="list">
                    <li>
                      <img
                        :src="order.good.imageURL"
                        alt=""
                        style="width: 100px; height: 100px"
                      />
                    </li>
                    <li>
                      <p>{{ order.good.name }}</p>
                    </li>
                    <li>
                      <h3>￥{{ order.good.price }}</h3>
                    </li>
                    <li>
                      <div>库存： {{ order.good.store }}</div>
                      <el-input-number
                        @change="handleChange"
                        v-model="order.good.orderNum"
                        :min="1"
                        :max="order.good.store - 0"
                        size="mini"
                        style="width: 80px"
                      >
                      </el-input-number>
                    </li>
                    <li>运费：0.00</li>
                    <li>
                      小计：
                      <span style="color: red">
                        ￥{{ order.good.orderNum * order.good.price }}
                      </span>
                    </li>
                    <li>
                      <communicate :seller="order.seller" />
                    </li>
                  </div>
                  <div style="margin-left: 2%; display: flex">
                    <h5 style="margin: 0; margin-right: 10px">给卖家留言</h5>
                    <el-input
                      type="textarea"
                      :rows="2"
                      placeholder="选填，请先和商家协商一致，付款后商家可见"
                      v-model="order.good.text"
                      maxlength="200"
                      show-word-limit
                      resize="none"
                      style="width: 80%"
                    />
                  </div>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div class="bill" style="border-top: solid 1px #c0c0f1">
          <h4 style="line-height: 50px; margin-top: 0">发票信息：</h4>
          <div style="padding-left: 15px">普通发票（电子） 个人 明细</div>
          <h5>使用优惠/抵用</h5>
        </div>
      </div>
      <div class="money">
        <ul>
          <li>
            <b>
              <span style="margin-right: 20px">
                {{ orderNum }}件商品，总商品金额
              </span>
            </b>
            <span style="color: red">¥{{ orderMoney }}</span>
          </li>
          <li v-show="radio1 == '线上'">
            <b>返现：</b>
            <span>0.00</span>
          </li>
          <li v-show="radio1 == '线上'">
            <b>运费：</b>
            <span>0.00</span>
          </li>
        </ul>
      </div>
      <div class="trade" v-show="radio">
        <div class="price">
          应付金额: <span>¥{{ orderMoney }}</span>
        </div>
        <div class="receiveInfo">
          寄送至:
          <span>
            {{ radio.grProvinces }}{{ radio.grCity }}{{ radio.grPrefecture
            }}{{ radio.grSpecificAddr }}
          </span>
          收货人：<span>{{ radio.grName }}</span>
          <span>{{ radio.grPhone }}</span>
        </div>
      </div>
      <div class="sub">
        <a class="subBtn" @click="submit">提交订单</a>
      </div>
    </div>
  </div>
</template>

<script>
import api from "../../api";
import communicate from "../../components/Communicate.vue";
import addressTree from "../../components/MessagePage/AddressTree";
import { mapState } from "vuex";
import base from "../../api/base";
export default {
  components: {
    communicate,
  },
  data() {
    var validateGrName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入您的收货人姓名!"));
      } else {
        callback();
      }
    };
    var validateGrPhone = (rule, value, callback) => {
      const reg =
        /^0?(13[0-9]|15[012356789]|18[0-9]|14[578]|16[6]|17[035768]|19[19])[0-9]{8}$/;
      if (value === "") {
        callback(new Error("请输入您的收货人电话!"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入合法的手机号!"));
      } else {
        callback();
      }
    };
    var validateLocation = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择收货所在地!"));
      } else {
        callback();
      }
    };
    var validateGrSpecificAddr = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入详细的收货地址!"));
      } else {
        callback();
      }
    };
    return {
      seller: "",
      orderIds: [],
      addressInformation: [
        {
          id: "",
          grName: "",
          grPhone: "",
          grSpecificAddr: "",
          grProvinces: "",
          grPrefecture: "",
          grCity: "",
          status: "",
        },
      ],
      radio: "",
      radio1: "",
      goodInfo: [
        {
          good: {
            id: "",
            imageURL: "",
            name: "",
            appearance: "",
            author: "",
            price: "",
            freight: "",
            store: "",
          },
          seller: {
            id: "",
            imageURL: "",
            nickname: "",
            isOnline: "",
          },
        },
      ],
      goodId: [],
      goodNum: [],
      orderNum: 0,
      orderMoney: 0,
      visable: false,
      emojiBody: true,
      inputText: "",
      chatList: [],
      OwOlist: [
        //表情包和表情路径
        { title: "微笑", url: "weixiao.gif" },
        { title: "嘻嘻", url: "xixi.gif" },
        { title: "哈哈", url: "haha.gif" },
        { title: "可爱", url: "keai.gif" },
        { title: "可怜", url: "kelian.gif" },
        { title: "挖鼻", url: "wabi.gif" },
        { title: "吃惊", url: "chijing.gif" },
        { title: "害羞", url: "haixiu.gif" },
        { title: "挤眼", url: "jiyan.gif" },
        { title: "闭嘴", url: "bizui.gif" },
        { title: "鄙视", url: "bishi.gif" },
        { title: "爱你", url: "aini.gif" },
        { title: "泪", url: "lei.gif" },
        { title: "偷笑", url: "touxiao.gif" },
        { title: "亲亲", url: "qinqin.gif" },
        { title: "生病", url: "shengbing.gif" },
        { title: "太开心", url: "taikaixin.gif" },
        { title: "白眼", url: "baiyan.gif" },
        { title: "右哼哼", url: "youhengheng.gif" },
        { title: "左哼哼", url: "zuohengheng.gif" },
        { title: "嘘", url: "xu.gif" },
        { title: "衰", url: "shuai.gif" },
        { title: "吐", url: "tu.gif" },
        { title: "哈欠", url: "haqian.gif" },
        { title: "抱抱", url: "baobao.gif" },
        { title: "怒", url: "nu.gif" },
        { title: "疑问", url: "yiwen.gif" },
        { title: "馋嘴", url: "chanzui.gif" },
        { title: "拜拜", url: "baibai.gif" },
        { title: "思考", url: "sikao.gif" },
        { title: "汗", url: "han.gif" },
        { title: "困", url: "kun.gif" },
        { title: "睡", url: "shui.gif" },
        { title: "钱", url: "qian.gif" },
        { title: "失望", url: "shiwang.gif" },
        { title: "酷", url: "ku.gif" },
        { title: "色", url: "se.gif" },
        { title: "哼", url: "heng.gif" },
        { title: "鼓掌", url: "guzhang.gif" },
        { title: "晕", url: "yun.gif" },
        { title: "悲伤", url: "beishang.gif" },
        { title: "抓狂", url: "zhuakuang.gif" },
        { title: "黑线", url: "heixian.gif" },
        { title: "阴险", url: "yinxian.gif" },
        { title: "怒骂", url: "numa.gif" },
        { title: "互粉", url: "hufen.gif" },
        { title: "书呆子", url: "shudaizi.gif" },
        { title: "愤怒", url: "fennu.gif" },
        { title: "感冒", url: "ganmao.gif" },
        { title: "心", url: "xin.gif" },
        { title: "伤心", url: "shangxin.gif" },
        { title: "猪", url: "zhu.gif" },
        { title: "熊猫", url: "xiongmao.gif" },
        { title: "兔子", url: "tuzi.gif" },
        { title: "喔克", url: "ok.gif" },
        { title: "耶", url: "ye.gif" },
        { title: "棒棒", url: "good.gif" },
        { title: "不", url: "no.gif" },
        { title: "赞", url: "zan.gif" },
        { title: "来", url: "lai.gif" },
        { title: "弱", url: "ruo.gif" },
        { title: "草泥马", url: "caonima.gif" },
        { title: "神马", url: "shenma.gif" },
        { title: "囧", url: "jiong.gif" },
        { title: "浮云", url: "fuyun.gif" },
        { title: "给力", url: "geili.gif" },
        { title: "围观", url: "weiguan.gif" },
        { title: "威武", url: "weiwu.gif" },
        { title: "话筒", url: "huatong.gif" },
        { title: "蜡烛", url: "lazhu.gif" },
        { title: "蛋糕", url: "dangao.gif" },
        { title: "发红包", url: "fahongbao.gif" },
      ],

      addVisable: false,
      addAddressInfoTemp: {
        location: "",
        idTemp: "",
        grNameTemp: "",
        grPhoneTemp: "",
        grSpecificAddrTemp: "",
        grProvincesTemp: "",
        grPrefectureTemp: "",
        grCityTemp: "",
        statusTemp: "",
      },
      locationTree: "",
      rules: {
        grNameTemp: [
          {
            validator: validateGrName,
            trigger: "blur",
          },
        ],
        grPhoneTemp: [
          {
            validator: validateGrPhone,
            trigger: "blur",
          },
        ],
        location: [
          {
            validator: validateLocation,
            trigger: "blur",
          },
        ],
        grSpecificAddrTemp: [
          {
            validator: validateGrSpecificAddr,
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("login", ["user"]),
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    addAddressSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = new URLSearchParams();
          param.append("userId", this.user.userId);
          param.append("grName", this.addAddressInfoTemp.grNameTemp);
          param.append("grPhone", this.addAddressInfoTemp.grPhoneTemp);
          param.append(
            "grSpecificAddr",
            this.addAddressInfoTemp.grSpecificAddrTemp
          );
          param.append("grProvinces", this.addAddressInfoTemp.location[0]);
          if (this.addAddressInfoTemp.location.length == 2) {
            param.append("grCity", this.addAddressInfoTemp.location[1]);
            param.append("grPrefecture", "");
          } else if (this.addAddressInfoTemp.location.length == 3) {
            param.append("grCity", this.addAddressInfoTemp.location[1]);
            param.append("grPrefecture", this.addAddressInfoTemp.location[2]);
          }
          param.append("status", "0");
          api.addGoodsReceiveInfo(param).then((res) => {
            console.log(res.data);
            if (res.data != "-1") {
              let param = new URLSearchParams();
              param.append("userId", this.user.userId);
              api.getGoodsReceiveInfo(param).then((res) => {
                this.addressInformation = res.data;
                this.$message({
                  message: "收货信息保存成功!",
                  type: "success",
                });
                this.addVisable = false;
                this.resetForm("addAddressInfoTemp");
              });
            }
          });
        } else {
          return;
        }
      });
    },
    grPhoneInput(val) {
      let codeReg = new RegExp("[0-9]+"), //正则 数字；
        len = val.length,
        str = "";
      for (var i = 0; i < len; i++) {
        if (codeReg.test(val[i])) {
          str += val[i];
        }
      }
      this.addAddressInfoTemp.grPhoneTemp = str;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    submit() {
      if (!this.radio1) {
        this.$message.error("请选择您的交易方式");
        return;
      } else if (this.radio1 == "线上") {
        if (!this.radio) {
          this.$message.error("请选择您的收货地址");
          return;
        }
        for (let i = 0; i < this.goodInfo.length - 1; i++) {
          let params = new URLSearchParams();
          params.append("userId", this.user.userId);
          params.append("goodId", this.goodInfo[i].good.id);
          params.append("goodNum", this.goodInfo[i].good.orderNum);
          params.append("tradeWay", this.radio1);
          params.append("grId", this.radio.id);
          params.append("remark", this.goodInfo[i].good.text);
          api.submitOrder(params).then((res) => {
            if (res.data != "-1") {
              this.orderIds.push(res.data);
            } else {
              console("error");
            }
          });
        }
        let len = this.goodInfo.length - 1;
        let params = new URLSearchParams();
        params.append("userId", this.user.userId);
        params.append("goodId", this.goodInfo[len].good.id);
        params.append("goodNum", this.goodInfo[len].good.orderNum);
        params.append("tradeWay", this.radio1);
        params.append("grId", this.radio.id);
        params.append("remark", this.goodInfo[len].good.text);
        api.submitOrder(params).then((res) => {
          if (res.data != "-1") {
            this.$message({
              message: "订单生成成功，请支付",
              type: "success",
            });
            let time = Date.parse(new Date());
            console.log(time);
            this.orderIds.push(res.data);
            this.$router.push({
              path: "/pay",
              query: {
                money: this.orderMoney,
                orderIds: this.orderIds,
                time: time,
              },
            });
          }
        });
      } else {
        this.$confirm(
          "您选择了线下面交，请确认是否与商家协商好线下面交细节?",
          "提示",
          {
            confirmButtonText: "确定提交",
            cancelButtonText: "返回协商",
            type: "warning",
          }
        )
          .then(() => {
            for (let i = 0; i < this.goodInfo.length - 1; i++) {
              let params = new URLSearchParams();
              params.append("userId", this.user.userId);
              params.append("goodId", this.goodInfo[i].good.id);
              params.append("goodNum", this.goodInfo[i].good.orderNum);
              params.append("tradeWay", this.radio1);
              params.append("grId", this.radio.id);
              params.append("remark", this.goodInfo[i].good.text);
              api.submitOrder(params).then((res) => {
                if (res.data != "-1") {
                  this.orderIds.push(res.data);
                } else {
                  console("error");
                }
              });
            }
            let len = this.goodInfo.length - 1;
            let params = new URLSearchParams();
            params.append("userId", this.user.userId);
            params.append("goodId", this.goodInfo[len].good.id);
            params.append("goodNum", this.goodInfo[len].good.orderNum);
            params.append("tradeWay", this.radio1);
            params.append("grId", this.radio.id);
            params.append("remark", this.goodInfo[len].good.text);
            api.submitOrder(params).then((res) => {
              if (res.data != "-1") {
                this.$message({
                  message: "订单生成成功，请支付",
                  type: "success",
                });
                let time = Date.parse(new Date());
                console.log(time);
                this.orderIds.push(res.data);
                this.$router.push({
                  path: "/pay",
                  query: {
                    money: this.orderMoney,
                    orderIds: this.orderIds,
                    time: time,
                  },
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消订单提交",
            });
          });
      }
    },
    handleChange(value) {
      this.orderNum = 0;
      this.orderMoney = 0;
      for (let i = 0; i < this.goodInfo.length; i++) {
        this.orderNum += this.goodInfo[i].good.orderNum;
        this.orderMoney +=
          this.goodInfo[i].good.orderNum * this.goodInfo[i].good.price;
      }
    },
    downLine(val) {
      this.$message.warning(
        "若为线下面交，请务必提交订单之前先与商家协商好线下面交!"
      );
    },
    handleClose(done) {
      this.resetForm("addAddressInfoTemp");
      done();
    },
  },
  created() {
    if (!this.$route.query.goodId) {
      this.$router.push({ path: "/" });
    }
    this.goodId = this.$route.query.goodId;
    let params = new URLSearchParams();
    params.append("goodIds[]", this.goodId);
    api.getCreateOrdersInfo(params).then((res) => {
      this.goodInfo = res.data;
      for (let i = 0; i < this.goodInfo.length; i++) {
        this.goodInfo[i].good.imageURL =
          base.baseUrl + this.goodInfo[i].good.imageURL;
        this.goodInfo[i].good.orderNum = 1;
        this.goodInfo[i].good.text = "";
        this.orderNum++;
        this.orderMoney += this.goodInfo[i].good.price;
      }
      // console.log(this.goodInfo);
    });
    let param = new URLSearchParams();
    param.append("userId", this.user.userId);
    api.getGoodsReceiveInfo(param).then((res) => {
      this.addressInformation = res.data;
      console.log(this.addressInformation);
    });
    this.locationTree = addressTree.locationTree;
  },
};
</script>

<style lang="less" scoped>
.main {
  border-radius: 4px;
  padding-bottom: 20px;
  width: 90%;
  min-height: 100%;
  overflow: auto;
  text-align: left;
  padding-left: 2.5%;
  padding-right: 2.5%;
  margin-left: 5%;
  margin-bottom: 30px;
  border: 1px solid #ddd;
  background-color: snow;
  box-shadow: 2px 2px 5px #909090;
  .addressTable {
    width: 100%;
    ::v-deep .el-table .el-table__cell {
      padding: 10px 0;
    }
    .el-table__row-current-row {
      background-color: #d84242;
    }
    ::v-deep .el-table__cell {
      height: 14px;
      font-size: 16px;
      border: 1px solid #ebeef5;
    }
    ::v-deep .cell {
      text-align: left;
      font-size: 14px;
    }
  }
  .good .list {
    margin-left: 0%;
    display: flex;
    font-size: 14px;
    // justify-content: space-between;
    li {
      margin: auto auto;
      line-height: 30px;
      p {
        margin-bottom: 20px;
      }
      h4 {
        color: #c81623;
        font-weight: 400;
      }
      h3 {
        color: #e12228;
      }
    }
  }
  .money {
    width: 100%;
    margin: 20px auto;
    height: 70px;
    ul {
      width: 280px;
      float: right;
      margin-top: 0;
      li {
        // line-height: 30px;
        display: flex;
        justify-content: space-between;
        i {
          color: red;
        }
      }
    }
  }
  .trade {
    box-sizing: border-box;
    width: 100%;
    padding: 10px;
    margin: 10px auto;
    text-align: right;
    background-color: #f4f4f4;
    border: 1px solid #ddd;
    div {
      line-height: 30px;
    }
    .price span {
      color: #e12228;
      font-weight: 700;
      font-size: 14px;
    }
    .receiveInfo {
      color: #999;
    }
  }
  .sub {
    width: 100%;
    margin: 0 auto 10px;
    .subBtn {
      float: right;
      width: 164px;
      height: 56px;
      font: 700 18px "微软雅黑";
      line-height: 56px;
      text-align: center;
      color: #fff;
      background-color: #e1251b;
    }
  }
}
</style>